package com.baibei.basic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.utils.TextUtils;
import com.baibei.module.BasicFragment;
import com.baibei.module.BuildConfig;
import com.baibei.module.R;
import com.baibei.widget.RaeWebChromeClient;
import com.baibei.widget.RaeWebView;
import com.baibei.widget.RaeWebViewClient;
import com.blankj.utilcode.utils.ToastUtils;
import com.rae.widget.RaePlaceHolderLayout;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.util.List;


/**
 * 网页查看
 * Created by ChenRui on 2016/12/27 23:07.
 */
public class WebViewFragment extends BasicFragment {

    private String mUrl;
    private String mRawUrl;
    private WebViewClient mRaeWebViewClient;
    private OnFragmentListener mOnFragmentListener;

    /**
     * form表单数据
     */
    private String mHtmlText;

    public static WebViewFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("url", url);
        WebViewFragment fragment = new WebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 根据form数据界面
     *
     * @param html html
     * @return WebViewFragment
     */
    public static WebViewFragment newInstanceByHtml(String html) {
        Bundle args = new Bundle();
        args.putString("form", html);
        WebViewFragment fragment = new WebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    protected WebView mWebView;

    FrameLayout mContentLayout;

    protected RaePlaceHolderLayout mPlaceHolderLayout;

    protected ProgressBar mProgressBar;


    @Override
    protected void onBindView(View view) {
        mContentLayout = view.findViewById(R.id.content);
        mProgressBar = view.findViewById(R.id.pb_web_view);
        mPlaceHolderLayout = view.findViewById(R.id.placeholder);
        mWebView = getWebView();
        mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mContentLayout.addView(mWebView);
        mPlaceHolderLayout.setRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPlaceHolderLayout.dismiss();
                mWebView.reload();
            }
        });
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_webview;
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface", "JavascriptInterface"})
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDisplayZoomControls(false);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setUseWideViewPort(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        File cacheDir = getContext().getExternalCacheDir();

        if (cacheDir != null && cacheDir.canRead() && cacheDir.canWrite()) {
            settings.setAppCacheEnabled(true);
            settings.setAppCachePath(cacheDir.getPath());
        }


        mRaeWebViewClient = getWebViewClient();
        mWebView.setWebChromeClient(getWebChromeClient());
        mWebView.setWebViewClient(mRaeWebViewClient);
        mPlaceHolderLayout.dismiss();

        //加载url
        if (mWebView != null && mUrl != null) {
            loadUrl(getArguments().getString("url"));
        }
        //加载form
        if (mWebView != null && !TextUtils.isEmpty(mHtmlText)) {
            mWebView.loadData(mHtmlText, "text/html", "UTF-8");
        }
        //回调上层自行添加相应的交互
        if (mOnFragmentListener != null) {
            mOnFragmentListener.onReadyListener(this, mWebView);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mRawUrl = getArguments().getString("url");
            mHtmlText = getArguments().getString("form");
            mUrl = mRawUrl;
        }
    }

    @Override
    public void onDestroy() {
        mContentLayout.removeAllViews();
        mWebView.removeAllViews();
        if (mRaeWebViewClient != null && mRaeWebViewClient instanceof RaeWebViewClient) {
            ((RaeWebViewClient) mRaeWebViewClient).destroy();
        }
        mWebView.destroy();
        super.onDestroy();
    }

    public String getUrl() {
        return mWebView.getUrl();
    }


    public WebChromeClient getWebChromeClient() {
        return new RaeWebChromeClient(mProgressBar);
    }

    public WebViewClient getWebViewClient() {
        return new RaeWebViewClient(mProgressBar, mPlaceHolderLayout) {
            @Override
            protected void showEmpty() {
                super.showEmpty();
                if (getActivity() != null) {
                    getActivity().setTitle("网络连接失败");
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("weixin://wap/pay?")) {

                    if (!isWechatExist()) {
                        ToastUtils.showShortToast("请安装微信客户端");
                        return false;
                    }
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        };
    }

    private boolean isWechatExist() {
        IWXAPI wxapi = WXAPIFactory.createWXAPI(getContext(), BuildConfig.WECHAT_APP_ID);
        if (wxapi.isWXAppInstalled() && wxapi.isWXAppSupportAPI()) {
            return true;
        } else {
            PackageManager pm = getContext().getPackageManager();
            List<PackageInfo> pinfo = pm.getInstalledPackages(0);
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equalsIgnoreCase("com.tencent.mm")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public WebView getWebView() {
        return new RaeWebView(getContext().getApplicationContext());
    }

    public void loadUrl(String url) {
        mWebView.loadUrl(url);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentListener) {
            mOnFragmentListener = (OnFragmentListener) context;
        }
    }

    /**
     * callback
     */
    public interface OnFragmentListener {

        /**
         * 回调监听
         */
        void onReadyListener(Fragment fragment, WebView webView);
    }

}
